/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gossipinator;

import java.io.*;

/**
 *
 * @author cox
 */
public class ClientThread extends Thread {
        private static DataOutputStream outputDataStream;
        private static DataInputStream inputDataStream,inputDataStream2;

    public synchronized void run() {

        String date1,sender,message;
        byte[] byteInputData = new byte[300];
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
        Gossip gossip1;

        System.out.println("BT Client Thread starting");
        //while (true) {
        
            Controller.bt1.Client_Cherche_Serveur();
            System.out.println("BT client: found server");
            Controller.clientdidntfindserver=false;
            
            outputDataStream = Controller.bt1.Client_Ecriture();
            inputDataStream = Controller.bt1.Client_Lecture();

        while (true) {
        //{
           try{
                inputDataStream.read(byteInputData);
                inputStream = new ByteArrayInputStream(byteInputData);
                inputDataStream2 = new DataInputStream(inputStream);
//                System.out.println("Server read: " + byteInputData) ;
                date1 = new String(inputDataStream2.readUTF());
                sender = new String(inputDataStream2.readUTF());
                message = new String(inputDataStream2.readUTF());
                System.out.println("BT client receive: "+sender+" "+message);
                gossip1 = new Gossip(sender,message,date1);
                Controller.gossiplist1 += (gossip1.getHeader()+": "+gossip1.getMessage()+"\r\n");
            }     catch (Exception e) {
                System.out.println("Client Exception: " + e) ;
            }

            //Controller.bt1.Serveur_Fermer();
        }

    }

    public static synchronized void write(ByteArrayOutputStream os){
            //send gossip to server
        byte[] output;
        output = os.toByteArray();
        System.out.println("BT client: sending Gossip");
        try{
            outputDataStream.write(output);
        }     catch (Exception e) {
                System.out.println("Client Exception: " + e) ;
        }
    }

}
